package com.android.pandoid.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.android.pandoid.IAidlRemoteInterface;
import com.android.pandoid.IAidlSendMessageInterface;
import com.android.pandoid.IManagerAidlInterface;
import com.android.pandoid.IMessageReceiverListener;
import com.android.pandoid.aidl.entity.MessageBean;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import androidx.annotation.Nullable;

/**
 * Date: 2020/8/28 10:32
 * Author: Tatum
 * Description: 测试连接的服务
 */
public class AidilRemoteService extends Service {

    private boolean isConnected;
    private ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;
    private ScheduledFuture<?> scheduledFuture;
    private Handler handler = new Handler(Looper.getMainLooper());
    private RemoteCallbackList<IMessageReceiverListener> receiverListeners = new RemoteCallbackList<>();

    private IAidlRemoteInterface connectService = new IAidlRemoteInterface.Stub() {
        @Override
        public void connect() throws RemoteException {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            isConnected = true;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(AidilRemoteService.this, "connect", Toast.LENGTH_LONG).show();
                }
            });
            scheduledFuture = scheduledThreadPoolExecutor.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    //  receiverListeners.beginBroadcast() 只能調用一次
                    final int count = receiverListeners.beginBroadcast();
                    Log.d("yi", "--------------"+count);
                    for (int i=0; i < count;i++) {
                        MessageBean messageBean = new MessageBean();
                        messageBean.setContent("--从这里回调主进程-->message from remote");
                        try {
                            Log.d("yi", "-------send message to main-------");
                            // 从这里回调主进程
                            receiverListeners.getBroadcastItem(i).onReceiverMessage(messageBean);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                    receiverListeners.finishBroadcast();
                }
            }, 5000, 5000, TimeUnit.MILLISECONDS);
        }

        @Override
        public void disconnect() throws RemoteException {
            isConnected = false;
            if (scheduledFuture!=null)scheduledFuture.cancel(true);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(AidilRemoteService.this, "disconnect", Toast.LENGTH_LONG).show();
                }
            });
        }

        @Override
        public boolean isConnected() throws RemoteException {
            return isConnected;
        }
    };


    private IAidlSendMessageInterface sendMessageService = new IAidlSendMessageInterface.Stub() {
        @Override
        public void sendMessage(MessageBean message) throws RemoteException {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(AidilRemoteService.this, "子进程接收消息：" + message.getContent(), Toast.LENGTH_LONG).show();
                }
            });
            if (isConnected) {
                message.setSend(true);
            } else {
                message.setSend(false);
            }
        }

        @Override
        public void registMessageRecieverListener(IMessageReceiverListener messageReceiverListener) throws RemoteException {
            if (messageReceiverListener != null) {
                Log.d("yi", "添加监听器"+messageReceiverListener.getClass().getSimpleName());
                receiverListeners.register(messageReceiverListener);
            }
        }

        @Override
        public void unregistMessageRecieverListener(IMessageReceiverListener messageReceiverListener) throws RemoteException {
            if (messageReceiverListener != null) {
                Log.d("yi", "移除监听器"+messageReceiverListener.getClass().getSimpleName());
                receiverListeners.unregister(messageReceiverListener);
            }
        }
    };
    private IManagerAidlInterface managerAidlInterface = new IManagerAidlInterface.Stub() {
        @Override
        public IBinder getAidlServiceInterface(String aidlServiceName) throws RemoteException {
            if (aidlServiceName.equals(IAidlSendMessageInterface.class.getSimpleName())) {
                return sendMessageService.asBinder();
            } else if (aidlServiceName.equals(IAidlRemoteInterface.class.getSimpleName())) {
                return connectService.asBinder();
            } else {
                return null;
            }
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return managerAidlInterface.asBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();

        scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);

    }
}
